package com.zlcx.tz.live.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zlcx.tz.live.client.GroupClient;
import com.zlcx.tz.live.constant.ResultStatus;
import com.zlcx.tz.live.exception.CheckRunException;
import com.zlcx.tz.live.utils.SignUtil;
import com.zlcx.tz.live.vo.GroupVO;
import com.zlcx.tz.live.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p></p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author zl
 * @version 1.0
 * @date Created in 2019/4/19 14:32
 * @copyright: Copyright (c) founders
 */
@Service
@Slf4j
public class GroupService {

    @Autowired
    GroupClient groupClient;

    @Value("${shangde.sign.secret}")
    String secret;

    public List<GroupVO> myGroupList(Long userId){

        ResultVO resultVO =null;
        List<GroupVO> list = Lists.newArrayList();
        try {
            long t1 = System.currentTimeMillis();

            Map<String, String[]> requestParams = new HashMap<>(1);
            requestParams.put("userId",new String[]{String.valueOf(userId)});
            requestParams.put("toUserId",new String[]{String.valueOf(userId)});
            String sig = SignUtil.sign(secret, requestParams);
            resultVO = groupClient.myGroups(sig,userId,userId);
            long t2 = System.currentTimeMillis();
            log.info("查询用户所在组列表信息cost:{}ms，sig={},userId={},resultVO={}",t2-t1,sig,userId, JSON.toJSONString(resultVO));
            if(resultVO==null || resultVO.getCode()==null || ResultStatus.SUCCESS.getCode()!=resultVO.getCode()){
                log.error("查询用户所在组列表信息失败，cost:{}ms，sig={},userId={},resultVO={}",t2-t1,sig,userId, JSON.toJSONString(resultVO));
                throw new CheckRunException("查询用户所在组列表信息失败：userId="+userId);
            }

            if(resultVO.getData() != null){
                list = JSON.parseArray(JSON.toJSONString(resultVO.getData()),GroupVO.class);
            }
        } catch (Exception e) {
            log.error("查询用户所在组列表信息失败，userId={},resultVO={},e={}",userId, JSON.toJSONString(resultVO),e);
        }

        return list;
    }


}
